package com.third.customer.site.support;

import com.third.customer.model.data.JsonResult;
import com.third.customer.service.exception.ThirdBadRequestException;
import com.third.customer.service.exception.ThirdForbiddenException;
import com.third.customer.service.exception.ThirdNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * Created by hehuaichun on 2019/12/25.
 */
@ControllerAdvice
@Slf4j
public class BaseHandler {

    @ExceptionHandler(value = {
            MethodArgumentNotValidException.class,
            ServletRequestBindingException.class,
            ThirdBadRequestException.class})
    public JsonResult badRequest(Exception ex) {
        if (ex instanceof MethodArgumentNotValidException) {
            //嵌套参数验证报错抛出MethodArgumentNotValidException异常,
            // 嵌套参数使用@Valid注解,如果出现校验不过的情况,通过此方法提示信息
            MethodArgumentNotValidException methodException = (MethodArgumentNotValidException) ex;
            String msg = methodException.getBindingResult().getFieldError().getField()
                    + methodException.getBindingResult().getFieldError().getDefaultMessage();
            log.error(msg, ex);
            return JsonResult.badRequest(msg);
        } else {
            log.error(ex.getMessage(), ex);
            return JsonResult.badRequest(ex.getMessage());
        }
    }

    @ExceptionHandler(value = {
            ThirdForbiddenException.class})
    public JsonResult forbidden(Exception ex) {
        log.error(ex.getMessage(), ex);
        return JsonResult.forbidden(ex.getMessage());
    }

    @ExceptionHandler(value = {
            ThirdNotFoundException.class})
    public JsonResult notFound(Exception ex) {
        log.error(ex.getMessage(), ex);
        return JsonResult.notFound(ex.getMessage());
    }
}
